﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using M.Core;
using M.ServiceApi1.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RpcService.Api1Service;
using static M.Core.ConsulExtensions;
using static M.Core.ServiceExtensions;

namespace M.ServiceApi1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConsul();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            ServiceOptions serviceEntity = new ServiceOptions()
            {
                ConsulIP = Configuration["Consul:IP"],
                ConsulPort = Convert.ToInt32(Configuration["Consul:Port"]),
                IP = Configuration["Consul:IIS.IP"],
                Port = Convert.ToInt32(Configuration["Consul:IIS.Port"]),
                Version = (float)Convert.ToDouble(Configuration["Version"]),
                ThriftPort = Convert.ToInt32(Configuration["Consul:Thrift.Port"])
            };

            //初始化Thrift服务
            app.UseThriftService(serviceEntity.ThriftPort, multiplexed =>
            {
                var userService = new UserServiceImpl();
                var orderService = new OrderServiceImpl();

                var userProcessor = new IUserService.AsyncProcessor(userService);
                var orderProcessor = new IOrderService.AsyncProcessor(orderService);

                multiplexed.RegisterProcessor("UserService", userProcessor);
                multiplexed.RegisterProcessor("OrderService", orderProcessor);
            });


            app.UseConsul(serviceEntity);
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}
